package repositories

import (
	"book-management-system/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

// CreateBorrowRecord 创建新的借书记录
func CreateBorrowRecord(tx *gorm.DB, userID, bookID string) error {
	borrowRecord := models.BorrowRecord{
		UserID:     stringToUint(userID),
		BookID:     stringToUint(bookID),
		BorrowedAt: time.Now(),
	}
	return tx.Create(&borrowRecord).Error
}

// GetBorrowRecord 获取未归还的借书记录
func GetBorrowRecord(tx *gorm.DB, userID, bookID string) (*models.BorrowRecord, error) {
	var record models.BorrowRecord
	if err := tx.Where("user_id = ? AND book_id = ? AND returned_at IS NULL", userID, bookID).First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

// MarkAsReturned 标记书籍为已归还
func MarkAsReturned(tx *gorm.DB, record *models.BorrowRecord) error {
	returnedAt := time.Now()
	record.ReturnedAt = &returnedAt
	return tx.Save(record).Error
}

// GetBooksBorrowedByUser 获取用户借阅的所有图书
func GetBooksBorrowedByUser(userID string) ([]models.Book, error) {
	var books []models.Book
	if err := DB.Joins("JOIN borrow_records ON borrow_records.book_id = books.id").
		Where("borrow_records.user_id = ? AND borrow_records.returned_at IS NULL", userID).
		Find(&books).Error; err != nil {
		return nil, err
	}
	return books, nil
}

// stringToUint 工具函数：将字符串转换为 uint
func stringToUint(s string) uint {
	var result uint
	fmt.Sscan(s, &result)
	return result
}
